import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Row, Col, Alert, Form, Input, Descriptions, Select, Modal } from 'antd';
import moment from 'moment';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin, { Draggable } from '@fullcalendar/interaction';
import {  afterCloseModal } from '@/utils/utils';
import '@fullcalendar/core/main.css';
import '@fullcalendar/daygrid/main.css';
import '@fullcalendar/timegrid/main.css';
import request from '@/utils/request';
import ZImg from 'react-zmage';
import BuildModalTitle from '@/components/BuildModalTitle';
import Detail from './Detail';

const { Option } = Select;
const repeatMap = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
const FormItem = Form.Item;

function tips(type, title) {
  message.destroy();
  message[type](title);
}

let matchList = [
  {
    id: '1',
    name: '第一个任务',
    startTime: '2021-06-30',
    endTime: '2021-06-30',
    repeatExecute: false,
    noEditable: true,
  },
  {
    id: '2',
    name: '第二个任务',
    startTime: '2021-06-29 09:45:23',
    endTime: '2021-06-29 15:10:23',
    repeatExecute: false,
    noEditable: true,
  },
  {
    id: '3',
    name: '第三个任务',
    startTime: '2021-06-07 00:00:00',
    endTime: '2021-06-08 00:00:00',
    repeatExecute: false,
    noEditable: true,
  },
  {
    id: '4',
    name: '第四个任务第四个任务',
    startTime: '2021-06-17 14:49:05',
    endTime: '2021-06-17 15:15:05',
    repeatExecute: false,
    noEditable: true,
  },
];

let repeatMatchList = [
  {
    id: '5',
    name: '每周一，周三重复任务',
    startDate: '2019-12-10', // 任务创建于12月10日
    startTime: '09:10:00', // 每次任务的开始时间
    endTime: '17:30:23', // 每次任务的结束时间
    repeatDates: ['星期一', '星期三'],
    repeatExecute: true,
  },
  {
    id: '6',
    name: '每周二重复任务',
    startDate: '2019-12-02', // 任务创建于12月2日
    startTime: '15:10:00', // 每次任务的开始时间
    endTime: '17:30:23', // 每次任务的结束时间
    repeatDates: ['星期二'],
    repeatExecute: true,
  },
];

class CalendarDemo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      oldYM: null, // 上次的年月
      all_users_reviewer: [],
      all_users_rehearer: [],
      start: '',
      end: '',
      periods: [],
      editRecord:{}

    };
    // 日历实例
    this.myRef = React.createRef();
  }

  includes = (arr1, arr2) => {
    return arr2.every(val => arr1.includes(val));
  };
  fetAllUser = (type, value) => {
    const that = this;
    request(`/all_staffs`, {
      method: 'GET',
      params: {
        department_id:type==='all_users_rehearer'?'253950250807472128':''
      },
    }).then((response) => {
      console.log('all_structures', response);
      if (response.status === 200) {
        that.setState({
          [type]: response.data.data,
        });
      }
    });
  };

  componentDidMount() {
    this.fetAllUser('all_users_reviewer');
    this.fetAllUser('all_users_rehearer');

    var containerEl = document.getElementById('external-events');
    new Draggable(containerEl, {
      itemSelector: '.fc-event-enable',
      eventData: function(eventEl) {
        console.log('eventEl', eventEl);
        return {
          title: '本次预订',
        };
      },
    });
    const that = this;
    console.log('this.myRef', this.myRef);
    let start = moment().add(-1, 'month').format('YYYY-MM-DD');
    let end = moment().add(1, 'month').format('YYYY-MM-DD');
    this.fetchPeriods(start, end);
    if (this.props.type === 'edit') {
      this.setState({
        start: this.props.editRecord.start_time,
        end: this.props.editRecord.end_time,
      });
      setTimeout(function() {
        console.log(that.myRef.current.calendar.getDate());
        that.myRef.current.calendar.gotoDate(moment(
          that.props.editRecord.start_time).format('YYYY-MM-DD'));
      }, 500);
    }
  }

  fetchPeriods = (start, end) => {
    const that = this;
    request(`/car_periods`, {
      method: 'GET',
      params: {
        car_id: this.props.type === 'edit' ? this.props.editRecord.car.id : this.props.editRecord.id,
        start_date: start,
        end_date: end,
      },
    }).then((response) => {
      console.log('periods', response);
      if (response.status === 200) {
        let data = response.data.data;
        let parseData = [];
        that.setState({
          periods: response.data.data,
        });
      }
    });
  };

  eventClick = eventInfo => {
    console.log(eventInfo);
    console.log(eventInfo.event._def);
    if(eventInfo.event._def.extendedProps.user){
      this.setState({
        editRecord:eventInfo.event._def.extendedProps,
        itemModal:true
      })
    }

  };
  // 获取非重复任务列表
  getMatchList = (year, month) => {
  };


  render() {
    console.log('this.state.periods', this.state.periods);
    let matchList = this.state.periods;

    matchList && matchList.forEach(item => {


      if(item.start_time.indexOf('00:00:00')>0&&item.end_time.indexOf('00:00:00')>0){
        item.start=moment(item.start_time).format('YYYY-MM-DD')
        let day=(moment(item.end_time).valueOf()-moment(item.start_time).valueOf())/86400000;
        item.end=moment(item.start_time).add(day,'day').format('YYYY-MM-DD')
      }else{
        item.start = item.start_time;
        item.end = item.end_time;
      }
      if (item.status === 1) {
        item.title = '可预订';
        item.backgroundColor = '#00c10b';
        item.textColor = '#fff';
        item.editable = true;
      } else if (item.status === 2) {
        item.title = `${item.user.name} 已预订`;
        item.backgroundColor = '#cf3b00';
        item.textColor = '#fff';
      } else if (item.status === 3) {
        item.title = '不可用';
        item.backgroundColor = '#6d6d6d';
        item.textColor = '#fff';
      }
      if (this.props.type === 'edit' && item.car_application_id === this.props.editRecord.id) {
        item.title = '本次预定';
        item.backgroundColor = '#0085ff';
        item.textColor = '#fff';
        item.editable = true;
      } else {
        item.editable = false;
      }

    });
    console.log('matchList', matchList);
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: { span: 10 },
        sm: { span: 10 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
      },
    };

    const { getFieldDecorator } = this.props.form;
    const that = this;

    return (
      <div>
        <div style={{ marginBottom: '12px' }}>
          <Alert message="拖动左侧蓝色区域到右侧'月视图'默认占据一整天时间，如果需要选择某几个小时，请切换到'周视图'选择" type="info"/>
        </div>
        <Row gutter={16}>
          <Col span={4}>
            <div id='external-events' style={{ fontSize: '14px' }}>
              <p>
                <strong>下方蓝色框可以拖动</strong>
              </p>
              <div className='fc-event'
                   style={{ marginBottom: '8px', background: '#cf3b00', color: '#fff', padding: '5px' }}>已预订
              </div>
              <div className='fc-event'
                   style={{ marginBottom: '8px', background: '#6d6d6d', color: '#fff', padding: '5px' }}>不可用
              </div>
              <div className='fc-event'
                   style={{ marginBottom: '8px', background: '#00c10b', color: '#fff', padding: '5px' }}>可预订
              </div>
              {
                this.props.type !== 'edit' &&
                <div className='fc-event fc-event-enable' style={{ padding: '5px', cursor: 'move' }}>拖动至右侧选择预定时间</div>

              }
              <ZImg style={{ width: '100%', marginTop: '16px' }}
                    src={this.props.type === 'edit' ? this.props.editRecord.car.image_path :
                      this.props.editRecord.image_path}/>
            </div>

            <div style={{ marginTop: '12px' }}>
              <Form onSubmit={this.handleSubmit}>
                <FormItem
                  {...formItemLayoutWithLabel}
                  label={(
                    <span style={{ fontWeight: 'bold' }}>
              用车事由
            </span>
                  )}>
                  {getFieldDecorator('cause', {
                    initialValue: this.props.editRecord ? this.props.editRecord.cause : '',
                    rules: [{ required: true, message: '用车事由不能为空' }],
                  })(
                    <Input/>,
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayoutWithLabel}
                  label={(
                    <span style={{ fontWeight: 'bold' }}>
              审批人
            </span>
                  )}>
                  {getFieldDecorator('reviewer_ids', {
                    rules: [{ required: true }],
                    initialValue: (this.props.editRecord && this.props.type === 'edit') ? this.props.editRecord.reviewers.map((item, index) => {
                      return {
                        key: `${item.user_id}#${item.name}`,
                        label: item.name,
                      };
                    }) : [],
                  })(
                    <Select labelInValue={true} mode="multiple" showSearch>
                      {
                        this.state.all_users_reviewer.map((item, index) => {
                          return <Option key={index} value={`${item.id}#${item.name}`}>
                            {item.name}
                          </Option>;
                        })
                      }
                    </Select>,
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayoutWithLabel}
                  label={(
                    <span style={{ fontWeight: 'bold' }}>
              抄送人
            </span>
                  )}>
                  {getFieldDecorator('replicator_ids', {
                    rules: [{ required: true }],
                    initialValue: (this.props.editRecord && this.props.type === 'edit') ? this.props.editRecord.replicators.map((item, index) => {
                      return {
                        key: `${item.user_id}#${item.name}`,
                        label: item.name,
                      };
                    }) : [],
                  })(
                    <Select  placeholder={'该处只显示“行政人事部”员工'} labelInValue={true} mode="multiple" showSearch>
                      {
                        this.state.all_users_rehearer.map((item, index) => {
                          return <Option key={index} value={`${item.id}#${item.name}`}>
                            {item.name}
                          </Option>;
                        })
                      }
                    </Select>,
                  )}
                </FormItem>
              </Form>
            </div>

          </Col>
          <Col span={20}>
            <FullCalendar
              ref={this.myRef}
              defaultView="dayGridMonth"
              plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
              header={{
                left: 'prev,next, today', // 上一年，上一月，下一月，下一年 今天
                center: 'title', // 当前年月
                right: 'dayGridMonth,timeGridWeek,timeGridDay', // 月 周 天
              }}
              locale='zh-cn'
              buttonText={{
                today: '今天',
                month: '月',
                week: '周',
                day: '天',
              }}
              allDayText='全天'
              firstDay={1}
              contentHeight={640}
              slotDuration={'01:00:00'}
              timeFormat={'HH:00:00'}
              slotLabelFormat={{
                hour: '2-digit',
                minute: '2-digit',
                meridiem: false,
                hour12: false,
              }}
              nowIndicator={true}
              editable={true}
              eventOverlap={true}
              eventClassNames={['myclassname', 'otherclassname']}
              eventSources={[matchList]}
              // events={function(event, end, callback){
              //   //prev上一月, next下一月等事件时调用
              //   console.log('start',moment(event.start).format('YYYY-MM-DD HH:mm:ss'))
              //   console.log('end',moment(event.end).format('YYYY-MM-DD HH:mm:ss'))
              //   return [matchList]
              // }}
              eventLimit={false}
              dateClick={(date)=>{
                console.log('date',date)
              }}
              customButtons={{
                prev: {
                  click: function() {
                    console.log('getDate()', that.myRef.current.calendar.getDate());
                    that.myRef.current.calendar.prev();
                    let start = moment(that.myRef.current.calendar.getDate()).add(-1, 'month').format('YYYY-MM-DD');
                    let end = moment(that.myRef.current.calendar.getDate()).add(1, 'month').format('YYYY-MM-DD');
                    that.fetchPeriods(start, end);
                  },
                },
                next: {
                  click: function() {
                    console.log('next');
                    console.log('getDate()', that.myRef.current.calendar.getDate());
                    that.myRef.current.calendar.next();
                    let start = moment(that.myRef.current.calendar.getDate()).add(-1, 'month').format('YYYY-MM-DD');
                    let end = moment(that.myRef.current.calendar.getDate()).add(1, 'month').format('YYYY-MM-DD');
                    that.fetchPeriods(start, end);
                  },
                },
                today: {
                  text: '返回今天',
                  click: function() {
                    console.log('today');
                    console.log('getDate()', that.myRef.current.calendar.getDate());
                    that.myRef.current.calendar.today();
                    let start = moment(that.myRef.current.calendar.getDate()).add(-1, 'month').format('YYYY-MM-DD');
                    let end = moment(that.myRef.current.calendar.getDate()).add(1, 'month').format('YYYY-MM-DD');
                    that.fetchPeriods(start, end);
                  },
                },
              }}
              eventClick={this.eventClick}
              droppable={true}  // this allows things to be dropped onto the calendar
              drop={function(info) {
                // is the "remove after drop" checkbox checked?
                console.log('drop', info);
                info.draggedEl.parentNode.removeChild(info.draggedEl);
                if (info.allDay) {
                  that.setState({
                    start: info.dateStr ? moment(info.dateStr).format('YYYY-MM-DD 00:00:00') : '',
                    end: info.dateStr ? moment(info.dateStr).add(1, 'days').format('YYYY-MM-DD 00:00:00') : '',
                  });
                } else {
                  that.setState({
                    start: info.dateStr ? moment(info.dateStr).format('YYYY-MM-DD HH:mm:ss') : '',
                    end: info.dateStr ? moment(info.dateStr).format('YYYY-MM-DD HH:mm:ss') : '',
                  });
                }

              }}
              eventDrop={function(info, delta, revertFunc, jsEvent, ui, view) {  //日程拖拽停止并且已经拖拽到其它位置了
                console.log('eventDrop', info.event);
                that.setState({
                  start: info.event.start ? moment(info.event.start).format('YYYY-MM-DD HH:mm:ss') : '',
                  end: info.event.end ? moment(info.event.end).format('YYYY-MM-DD HH:mm:ss') : '',
                });
              }
              }
              eventResize={function(info) {
                console.log('eventResize', info.event);
                that.setState({
                  start: info.event.start ? moment(info.event.start).format('YYYY-MM-DD HH:mm:ss') : '',
                  end: info.event.end ? moment(info.event.end).format('YYYY-MM-DD HH:mm:ss') : '',
                });
              }
              }
              eventTimeFormat={
                {
                  hour: '2-digit',
                  minute: '2-digit',
                  meridiem: false,
                  hour12: false,
                }
              }
            />
          </Col>
        </Row>
        <Modal
          title={<BuildModalTitle visible={this.state.itemModal} modalClass="itemModal"
                                  title={`详情`}/>}
          destroyOnClose
          visible={this.state.itemModal}
          centered
          className="itemModal"
          width={600}
          afterClose={() => {
            afterCloseModal(); // destroyOnClose需要
          }}
          footer={null}
          onCancel={() => {
            this.setState({ itemModal: false, editRecord: {} });
          }}

        >
          <Detail editRecord={this.state.editRecord}></Detail>
        </Modal>

      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(CalendarDemo);
export default (AddPoliciesFormWrap);
